package com.attrisoft.sanger.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.attrisoft.sanger.aws.S3Client;

public class Scheduler {
    
    public static final List<String> schedule(
        String user, String dir, String name, String email, String pre, String inflation) 
    {
        List<String> errors = new ArrayList<String>();
        
        if (workflowExists(user, name))
            errors.add("Workflow exists");
        
        if (!validAddress(email)) 
            errors.add("Email Address '" +email +"' is invalid");
        
        File reference = getReference(dir);
        if (reference == null)
            errors.add("Reference has not been uploaded");
        
        File sample = getSample(dir);
        if (sample == null)
            errors.add("Sample has not been uploaded");
        
        try {
            Float.parseFloat(pre);
        } catch (Exception nfe){
            errors.add("MCL Pre-Inflation '" +pre +"' is invalid");
        }
        try {
            Float.parseFloat(inflation);
        } catch (Exception nfe){
            errors.add("MCL Inflation '" +inflation +"' is invalid");
        }
        
        if (errors.size() < 1) {
            new Thread(new Workflow(user, name, email, reference, sample, pre, inflation)).start();
        }
        return errors;
    }
    
    private static boolean validAddress(String email) {
        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
        CharSequence inputStr = email;  
        Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
        Matcher matcher = pattern.matcher(inputStr);  
        return matcher.matches();
    }
    
    private static File getSample(String dir) {
        return getFile(dir, "sample");
    }
    
    private static File getReference(String dir) {
        return getFile(dir, "reference");
    }

    private static File getFile(String dir, String type) {
        File file = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader((dir +File.separator + type+".name")));
            String fname = reader.readLine();
            file = new File(dir +File.separator +fname);
            if (!file.exists())
                file = null;
        } catch (Exception e) { }
        return file;
    }

    private static boolean workflowExists(String user, String name) {
        return Workflow.exists(user, name) || S3Client.workflowExists(user, Workflow.getName(name));
    }
}
